package com.Java.train.common.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.Java.train.common.context.LoginMemberContext;
import com.Java.train.common.response.MemberLoginResp;
import com.Java.train.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class MemberInterceptor implements HandlerInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(MemberInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的token
        LOG.info("正在获取token");
        String token = request.getHeader("token");
        // 2.1 判断token是否存在
        if(StrUtil.isNotBlank(token)){
//            LOG.info("获取会员登录token:{}", token);
            JSONObject jsonObject = JwtUtil.getJSONObject(token);
            LOG.info("当前会员用户:{}", jsonObject);
            MemberLoginResp member = JSONUtil.toBean(jsonObject, MemberLoginResp.class);
            LoginMemberContext.setMember(member);
        }
        return true;
    }
}
